package services

import (
	"errors"
	"fmt"
	"log"
	"server/app/common/request"
	"server/app/common/response"
	"server/app/models"
	"server/global"
	"strconv"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

type videoService struct{}

var VideoService = new(videoService)

/* 视频列表 */
func (videoService *videoService) VideoList(params request.VideoList) (err error, paginatedVideos response.PaginatedResult) {
	//连表查询临时结构体
	type VideoWithUser struct {
		models.Videos
		Author string `json:"author" gorm:"column:author"`
	}
	var videosResult []VideoWithUser

	query := global.App.DB.Model(&models.Videos{})
	// 根据类型进行过滤
	if params.Type != "" {
		query = query.Where("type = ?", params.Type)
	}
	// 执行查询
	page := int(params.Page.Page)
	limit := int(params.Page.Limit)
	offset := (page - 1) * limit

	// 计算分页信息
	pagination, err := response.PaginateQuery(query, page, limit)
	if err != nil {
		return err, response.PaginatedResult{}
	}

	// 获取当前页的数据
	err = query.Offset(offset).Limit(limit).Joins("left join users on users.id =videos.user_id").Select("videos.*,users.name as author").Find(&videosResult).Error

	// 随机排序并获取当前页的数据
	// err = query.Order("RAND()").Offset(offset).Limit(limit).Find(&videos).Error//有性能问题

	if err != nil {
		log.Printf("[Error finding videos]视频查询错误: %v", err)
		return
	}
	var videoListRes []response.VideoListRes
	for _, video := range videosResult {
		videoListRes = append(videoListRes, response.VideoListRes{
			Id:          video.VideoID,
			Title:       video.Title,
			Description: video.Description,
			Author:      video.Author,
			AuthorId:    video.UserID,
			CoverPath:   video.CoverPath,
			Url:         video.VideoPath,
			Height:      200,
			Width:       200,
		})
	}

	// 设置分页结果
	paginatedVideos = response.PaginatedResult{
		Pagination: pagination,
		Records:    videoListRes,
	}

	return
}

/* 点赞功能 */
func (videoService *videoService) Like(params request.VideoLike) (err error) {
	//检查id
	targetVideo := global.App.DB.Where("video_id", params.VideoId).First(&models.Videos{})
	if targetVideo.Error != nil {
		return errors.New("找不到视频：" + targetVideo.Error.Error())
	}
	targetUser := global.App.DB.Where("id", params.UserId).First(&models.Users{})
	if targetUser.Error != nil {
		return errors.New("找不到用户：" + targetUser.Error.Error())
	}

	// 更新视频的点赞计数
	err = global.App.DB.Model(&models.Videos{}).Where("video_id = ?", params.VideoId).
		UpdateColumn("likes_count", gorm.Expr("likes_count + ?", 1)).Error
	if err != nil {
		return err
	}

	// 创建点赞记录
	like := models.Likes{
		VideoID: params.VideoId,
		UserID:  params.UserId,
	}
	err = global.App.DB.Create(&like).Error
	if err != nil {
		return err
	}

	return nil
}

/* 评论功能 */
func (videoService *videoService) Comment(params request.VideoComment) (err error) {
	//检查id
	targetVideo := global.App.DB.Where("video_id", params.VideoId).First(&models.Videos{})
	if targetVideo.Error != nil {
		return errors.New("找不到视频：" + targetVideo.Error.Error())
	}
	targetUser := global.App.DB.Where("id", params.UserId).First(&models.Users{})
	if targetUser.Error != nil {
		return errors.New("找不到用户：" + targetUser.Error.Error())
	}

	err = global.App.DB.Model(&models.Videos{}).Where("video_id = ?", params.VideoId).UpdateColumn("comments_count", gorm.Expr("comments_count + ?", 1)).Error
	if err != nil {
		return err
	}
	comment := models.Comments{
		VideoID: params.VideoId,
		UserID:  params.UserId,
		Content: params.Content,
	}
	err = global.App.DB.Create(&comment).Error
	if err != nil {
		return err
	}
	return nil
}

/* 评论列表 */
func (videoService *videoService) CommentList(params request.VideoCommentList) (err error, paginatedComments response.PaginatedResult) {
	var commentsList []models.Comments
	query := global.App.DB.Model(&models.Comments{}).Where("video_id = ?", params.VideoId)

	page := int(params.Page.Page)
	limit := int(params.Page.Limit)
	offset := (page - 1) * limit

	pagination, err := response.PaginateQuery(query, page, limit)

	if err != nil {
		return err, response.PaginatedResult{}
	}

	err = query.Offset(offset).Limit(limit).Find(&commentsList).Error
	if err != nil {
		log.Printf("Error finding comments: %v", err)
		return err, response.PaginatedResult{}
	}
	paginatedComments = response.PaginatedResult{
		Pagination: pagination,
		Records:    commentsList,
	}
	return
}

/* 视频详情 */
func (videoService *videoService) VideoDetail(params request.VideoDetail) (err error, result models.Videos) {
	err = global.App.DB.First(&result, params.VideoId).Error
	if err != nil {
		log.Println("VideoDetail-error", err)
		err = errors.New("查询失败")
		return
	}
	return
}

/* 删除视频 */
func (videoService *videoService) DeleteVideo(params request.DeleteVideo) (err error) {
	targetVideo := &models.Videos{}
	err = global.App.DB.Where("video_id = ?", params.VideoId).First(targetVideo).Error
	if err != nil {
		err = fmt.Errorf("视频查找失败: %w", err)
		global.App.Log.Error("视频查找失败", zap.Error(err))
		return
	}
	if targetVideo.UserID != params.UserId {
		err = errors.New("不是该视频的作者")
		global.App.Log.Error("不是该视频的作者", zap.Error(err))
		return
	}
	err = global.App.DB.Delete(targetVideo).Error
	if err != nil {
		err = fmt.Errorf("视频删除失败: %w", err)
		global.App.Log.Error("视频删除失败", zap.Error(err))
		return
	}
	return nil
}

/* 更新视频信息 */
func (videoService *videoService) UpdateVideo(userId string, params request.UpdateVideo) (err error) {
	var video models.Videos
	result := global.App.DB.Where("video_id = ?", params.VideoId).First(&video)
	if result.Error != nil {
		return fmt.Errorf("视频查找失败: %w", result.Error)
	}

	if strconv.Itoa(video.UserID) != userId {
		return errors.New("不是该视频的作者")
	}

	err = global.App.DB.Where("video_id=?", video.VideoID).Updates(models.Videos{
		Title:       params.Title,
		Description: params.Description,
	}).Error

	if err != nil {
		return err
	}

	return nil
}
